<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="姓名"></el-input>
                </el-form-item>
                <el-select v-model="filters.state" clearable placeholder="状态" >
                    <el-option label="禁用" value="-1"></el-option>
                    <el-option label="启用" value="0"></el-option>
                </el-select>
                <el-form-item>
                    <el-button type="primary" v-on:click="filtersloadDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-table :data="departments" v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60" label="序号">
            </el-table-column>
            <el-table-column prop="name" label="部门">
            </el-table-column>
            <el-table-column prop="sn" label="编号">
            </el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatState">
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理">
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门">
            </el-table-column>
            <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条分页条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增界面-->
        <el-dialog title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" :rules="rules" ref="ruleForm"  label-width="80px" >
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="sn">
                    <el-input v-model="addForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="0">启用</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门经理" prop="managerId">
                    <el-select v-model="addForm.managerId"  clearable placeholder="请选择">
                        <el-option
                                v-for="item in managers"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门">
                    <el-cascader  v-model="addForm.path"
                                  :options="parentDepartments"
                                  :props="{ checkStrictly: true }"
                                  clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" >提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<script>

    export default {
        data() {
            return {
                rules: {
                    name: [
                        {required: true, message: '部门名必填', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '编号必填', trigger: 'blur'}
                    ],
                    managerId: [
                        {required: true, message: '部门经理必选', trigger: 'change'}
                    ]
                },
                //上级所有的部门
                parentDepartments:[],
                //查询所有的部门经理
                managers:[],
                //添加及修改模态框显示的属性
                addForm:{
                    //部门id
                    id:'',
                    //部门名称
                    name:"",
                    //编号
                    sn:'',
                    //状态
                    state:'',
                    //部门经理
                    managerId:'',
                    //部门层级
                    path:''


                },
                //默认不弹出添加及修改模态框
                addFormVisible:false,
                //添加修改模态框的标题显示
                title:'',

                //高级查询的form表单
                filters:{
                    name:"",
                    state:''
                },

                //部门列表
                departments:[],
                //列表中选中的列
                sels: [],
                //当前页
                currentPage:1,
                //每页条数
                pageSize:10,
                //总条数
                total:0,
                //显示列表加载框
                listLoading:false,
            }
        },
        methods: {
            //查询所有部门树列表
            loadParentDepartments(){
                this.$http.patch("/department/findDepartmentTree").then(res => {
                    this.parentDepartments = res.data;
            });
            },

            //查询所有的部门经理
            loadManagers(){
                this.$http.patch("/department/findManagers").then(res=>{
                    this.managers = res.data;
            })
            },

            //给添加修改提交按钮注册事件
            addSubmit(){
                //manager 和parent没有相关属性与后台映射 故前台手动创建 相关对象
                //手动创建一个manager对象
                let manager = {"id":this.addForm.managerId};
                //手动给addFrom添加manager属性
                this.addForm.manager =manager;
                //获取addFrom的path属性----1，3,7
                let path = this.addForm.path;
                //手动创建parent对象------7
                let parent = {"id": path[path.length - 1]};
                this.addForm.parent = parent;
                //把path数组改为字符串      1,5,6
                if (path!=null){
                    this.addForm.path = path.toString();
                }
                console.debug(this.addForm)
                //提价from表单之前必须进行校验
                this.$refs["ruleForm"].validate((valid) => {
                    //校验成功才执行下面代码
                    if (valid) {
                        this.$http.post("/department", this.addForm).then(res => {
                            let {success, msg} = res.data;
                        if(success){
                            //关闭模态框
                            this.addFormVisible = false;
                            //刷新界面
                            this.loadDepartments();
                            //刷新上级部门
                            this.loadParentDepartments();
                        }else{
                            this.$message.error(msg);
                        }
                    });
                    }
                })

            },

            //点击添加触发事件
            handleAdd(){
                //设置添加标题
                this.title="添加";
                //先重置
                if(this.$refs["ruleForm"]){
                    //当出现了校验规则的时候，才能进行重置(上面判断的原因)
                    this.$refs["ruleForm"].resetFields();//this.$refs.ruleForm.resetFields()
                }
                //手动清空form表单
                for(var k in this.addForm){
                    this.addForm[k] = "";
                };
                //点击添加弹出模态框
                this.addFormVisible=true;
                //默认启用状态
                this.addForm.state = 0;
            },
            //格式化状态
            formatState(row, column){
                return row.state == 0 ? "启用" : "禁用";
            },
            //给编辑按钮注册事件
            handleEdit(index,row){
                //修改标题
                this.title = "修改";
                //能解决大部分的属性
                for(var k in this.addForm){
                    this.addForm[k] = row[k];
                }
                //对于特定属性，特定处理就可以了
                //给managerid赋值
                this.addForm.managerId = row.manager.id;
                //path应该改为数组
                if(this.addForm.path!=null){
                    this.addForm.path = this.addForm.path.split(",");
                }

                //弹出窗体
                this.addFormVisible = true;

            },
            //给删除按钮注册事件
            handleDel(index,row){
                this.$confirm('确定删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {//点击确定按钮，执行此函数中的内容
                    let para = { id: row.id };
                this.$http.delete("/department",{data:para}).then(res => {
                    let {success, msg} = res.data;
                if(success){
                    //提示成功信息
                    this.$message({
                        type: 'success',
                        message: msg
                    });
                    this.loadDepartments();
                }else{
                    this.$message.error(msg);
                }
            });
            }).catch(() => {//点击取消按钮的时候，执行此函数中的内容
                });
            },

            //高级查询调用的查询部门方法
            filtersloadDepartments(){
                this.currentPage = 1;
                this.loadDepartments();
            },

            //查询部门列表
            loadDepartments(){
                //显示加载框
                this.listLoading = true;
                //前端传递的分页参数(当前页，每页条数)
                let param = {"currentPage": this.currentPage, "pageSize": this.pageSize,
                    "name":this.filters.name,"state":this.filters.state};
                this.$http.patch("/department",param).then(res=>{
                    //关闭加载框
                    this.listLoading = false;
                let{list,total} = res.data;
                this.total = total;
                this.departments = list;

            })
            },

            //点击复选框触发该事件   vals返回选行对应的数据
            selsChange(vals){
                this.sels = vals;
            },
            //批量删除
            batchRemove(){
                this.$confirm('确定删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'

                }).then(() => {//点击确定按钮，执行此函数中的内容

                    let parm = this.sels;
                this.$http.delete("/department/batchRemove",{data:parm}).then(res => {
                    let {success, msg} = res.data;
                if(success){
                    //提示成功信息
                    this.$message({
                        type: 'success',
                        message: msg
                    });
                    this.loadDepartments();
                }else{
                    this.$message.error(msg);
                }
            });
            }).catch(() => {//点击取消按钮的时候，执行此函数中的内容
                });
            },
            //改变所选页触发该方法

            handleCurrentChange(val){
                //修改当前页
                this.currentPage = val;
                //再来分页查询
                this.loadDepartments();
            },
        },
        mounted() {
            //加载主页就加载列表
            this.loadDepartments();
            //加载所有的部门经理
            this.loadManagers();
            //加载部门级层
            this.loadParentDepartments();
        }
    }

</script>